package com.custom.base.base

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Typeface
import android.os.Build
import android.os.Build.VERSION.SDK_INT
import android.os.Build.VERSION_CODES.KITKAT
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import android.widget.Toast
import androidx.viewbinding.ViewBinding
import com.custom.base.R
import com.custom.base.databinding.ActBaseBinding
import com.custom.base.manager.SDActivityManager
import com.custom.base.manager.SDFragmentManager
import com.custom.base.type.AnimationActivityType
import com.custom.base.type.LinkageType
import com.custom.base.type.StatusBarType
import com.custom.base.util.IntentUtil
import com.custom.base.util.SDViewUtil
import com.google.android.material.appbar.AppBarLayout
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 作者：
 * 时间：2020/5/11
 * 描述：
 **/
abstract class BaseActivity<VB : ViewBinding>(private val inflate: (LayoutInflater) -> VB) :
    BaseAppCompatActivity() {
    private var mFragmentManager: SDFragmentManager? = null
    lateinit var viewBinding: VB
    private lateinit var actBaseBinding: ActBaseBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewBinding = inflate(layoutInflater)

        actBaseBinding = ActBaseBinding.inflate(LayoutInflater.from(this))
        setContentView(actBaseBinding.root)

        //setContentView(if(setTitleLayoutType() == BaseLayoutType.COLUMN) R.layout.act_base else R.layout.act_base_stack)
        setSupportActionBar(actBaseBinding.actBaseToolbar)
        mActivity = this
        SDActivityManager.instance.onCreate(this)
        val intent = intent
        if (intent == null) {
            initIntent(Intent())
            initParms(Bundle())
        } else {
            initIntent(intent)
            val bundle = intent.extras
            if (bundle == null) initParms(Bundle())
            else initParms(bundle)
        }
        initLayout()
        initTitle(setTitleVisibility())
        getSavedInstanceState(savedInstanceState)
        SDEventManager.register(this)

    }

//    protected abstract fun initViewBinding():VB

    /**
     * 初始化title
     */
    @SuppressLint("ObsoleteSdkInt")
    private fun initTitle(titleVisibility: Boolean) {
        if (!setFullScreen() && titleVisibility) {
            titleBackVisibility()
            getTitleTextView(actBaseBinding.actBaseTitleView)
            if (intent != null && intent.extras != null) {
                getTitleTextViewBundle(actBaseBinding.actBaseTitleView, intent.extras!!)
            } else {
                getTitleTextViewBundle(actBaseBinding.actBaseTitleView, Bundle())
            }
            if (isTitleBold()) actBaseBinding.actBaseTitleView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD))
            getToolbarView(actBaseBinding.actBaseToolbar)
            getTitleView(actBaseBinding.actBaseTitleLl)
            getAppBarLayoutView(actBaseBinding.ActBaseAppBarLayout)
            linkageTitleView(setTitleLinkage())
            setTitleRightTextView(setTitleRightTextView())
            setTitleRightImageView(setTitleRightImageView(), setTitleRightTextView())
            if (intent != null && intent.extras != null) {
                setTitleRightTextView(setTitleRightTextViewBundle(intent.extras!!))
                setTitleRightImageView(
                    setTitleRightImageViewBundle(intent.extras!!),
                    setTitleRightTextViewBundle(intent.extras!!)
                )
            } else {
                setTitleRightTextView(setTitleRightTextViewBundle(Bundle()))
                setTitleRightImageView(
                    setTitleRightImageViewBundle(Bundle()),
                    setTitleRightTextViewBundle(Bundle())
                )
            }
            actBaseBinding.actBaseBackIv.visibility = if (setShowTwoBackArrow()) View.GONE else View.VISIBLE
            actBaseBinding.actBaseBackIvTwo.visibility = if (setShowTwoBackArrow()) View.VISIBLE else View.GONE
            actBaseBinding.actBaseBackIv.setImageResource(setTitleBackRId())
            actBaseBinding.actBaseBackIvTwo.setImageResource(setTitleBackRIdTwo())
            actBaseBinding.actBaseToolbar.setBackgroundColor(setTitleBgColor())
            actBaseBinding.actBaseDividingLine.visibility =
                if (setTitleDividingLineVisibility()) View.VISIBLE else View.GONE
            if (SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                actBaseBinding.actBaseToolbar.fitsSystemWindows = true
            }
        } else {
            actBaseBinding.ActBaseAppBarLayout.visibility = View.GONE
            if (!setFullScreen()) {
                val layoutParams = SDViewUtil.layoutParamsRelativeLayoutMW
                layoutParams.topMargin = SDViewUtil.statusBarHeight
                actBaseBinding.actBaseContent.layoutParams = layoutParams
                actBaseBinding.actBaseLl.setBackgroundColor(setStatusBarColor())
            }
        }
        actBaseBinding.actBaseContent.setBackgroundColor(setBgColor())
        actBaseBinding.actBaseTitleRightLl.setBackgroundResource(setRightTitleBgRes())
        //设置状态栏颜色随toolbar
        if (SDK_INT >= KITKAT) {
            val localLayoutParams = window.attributes
            localLayoutParams.flags = FLAG_TRANSLUCENT_STATUS or localLayoutParams.flags
        }
        setStatusBarTextColor(setStatusBarType())
    }

    /**
     * 设置title右边文本集合
     */
    private fun setTitleRightTextView(textViews: List<String>) {
        for (i in textViews.indices) {
            val view = SDViewUtil.getRId(mActivity, R.layout.view_title_right_tv)
            val tv = view.findViewById<TextView>(R.id.view_title_right_tv)
            tv.text = textViews[i]
            tv.setTextColor(setTitleRightTextViewColor())
            view.setOnClickListener {
                onTitleRightClickListener(i, view)
                val intent = intent
                if (intent != null && intent.extras != null) {
                    onTitleRightClickListenerBundle(i, view, intent.extras!!)
                } else {
                    onTitleRightClickListenerBundle(i, view, Bundle())
                }
            }
            actBaseBinding.actBaseTitleRightLl.addView(view)
        }
    }

    /**
     * 设置title右边文本集合
     */
    fun upTitleRightTextView(textViews: List<String>) {
        actBaseBinding.actBaseTitleRightLl.removeAllViews()
        setTitleRightTextView(textViews)
    }

    /**
     * 设置title右边文本背景
     */
    fun upTitleRightTextView(resId: Int) {
        actBaseBinding.actBaseTitleRightLl.setBackgroundResource(resId)
    }

    /**
     * 设置title右边文本背景
     */
    fun upTitleBackground(resId: Int) {
        actBaseBinding.actBaseTitle.setBackgroundColor(resId)
    }

    /**
     * 设置title右边图片集合
     */
    private fun setTitleRightImageView(imageViews: List<Int>, textViews: List<String>) {
        for (i in imageViews.indices) {
            val view = SDViewUtil.getRId(mActivity, R.layout.view_title_right_iv)
            view.layoutParams = SDViewUtil.layoutParamsLinearLayoutWM
            val iv = view.findViewById<ImageView>(R.id.view_title_right_iv)
            iv.setImageResource(imageViews[i])
            view.setOnClickListener {
                onTitleRightClickListener(i + textViews.size, view)
                val intent = intent
                if (intent != null && intent.extras != null) {
                    onTitleRightClickListenerBundle(i + textViews.size, view, intent.extras!!)
                } else {
                    onTitleRightClickListenerBundle(i + textViews.size, view, Bundle())
                }
            }
            actBaseBinding.actBaseTitleRightLl.addView(view)
        }
    }

    /**
     * 设置title右边图片集合
     */
    fun upTitleRightImageView(imageViews: List<Int>, textViews: List<String>) {
        actBaseBinding.actBaseTitleRightLl.removeAllViews()
        setTitleRightImageView(imageViews, textViews)
    }

    /**
     * 设置状态栏字体颜色
     */
    private fun setStatusBarTextColor(statusBarType: StatusBarType) {
        if (SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            when (statusBarType) {
                StatusBarType.Light -> window.decorView.systemUiVisibility =
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE

                StatusBarType.Dark -> window.decorView.systemUiVisibility =
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            }
        }
    }

    /**
     * 初始化布局
     */
    private fun initLayout() {
        val layout = bindLayout()
        if (layout != 0) {
            //val contentView = layoutInflater.inflate(layout, null)
            viewBinding.root.layoutParams = SDViewUtil.layoutParamsRelativeLayoutMM
            actBaseBinding.actBaseContent.addView(viewBinding.root)
        }
    }

    /**
     * 更新title
     */
    fun upTitleText(text: String) {
        actBaseBinding.actBaseTitleView.text = text
    }

    /**
     * 更新返回键
     */
    fun upTitleBackVisibility(show: Boolean) {
        actBaseBinding.actBaseBackLl.visibility = if (show) View.VISIBLE else View.GONE
    }


    /**
     * 设置联动状态
     */
    private fun linkageTitleView(linkageType: LinkageType) {
        val toolbar = actBaseBinding.actBaseToolbar.layoutParams as AppBarLayout.LayoutParams
        when (linkageType) {
            LinkageType.SCROLL_SNAP -> toolbar.scrollFlags =
                AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP

            LinkageType.SCROLL_ENTER_ALWAYS -> toolbar.scrollFlags =
                AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS

            LinkageType.SCROLL_ENTER_ALWAYS_COLLAPSED -> toolbar.scrollFlags =
                AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED

            LinkageType.SCROLL_EXIT_UNTIL_COLLAPSED -> toolbar.scrollFlags =
                AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED

            LinkageType.SCROLL_ENTER_ALWAYS_ENTER_ALWAYS_COLLAPSED -> toolbar.scrollFlags =
                AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED

            LinkageType.NO -> {}
        }
    }

    /**
     * 设置是否显示返回键
     */
    private fun titleBackVisibility() {
        supportActionBar?.apply {
            val isBack = setTitleBackVisibility()
            if (isBack) {
                actBaseBinding.actBaseBackLl.visibility = View.VISIBLE
                actBaseBinding.actBaseBackLl.setOnClickListener {
                    onBackListener()
                }
            } else actBaseBinding.actBaseBackLl.visibility = View.GONE
        }
    }

    /**
     * back 和 menu 回调
     */
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            onHomeClickListener()
        } else onMenuClickListener(item.itemId)
        return super.onOptionsItemSelected(item)
    }

    /**
     * 设置menu
     */
    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        val menuId = setMenuId()
        if (menuId != 0) {
            menuInflater.inflate(menuId, menu)
            //如果存在menu就吧title往左边移动，保证title在中间
            val layoutParams = actBaseBinding.actBaseTitleView.layoutParams as RelativeLayout.LayoutParams
            layoutParams.leftMargin = actBaseBinding.actBaseBackLl.layoutParams.width
            actBaseBinding.actBaseTitleView.layoutParams = layoutParams
        }
        return menuId != 0
    }

    /**
     * 获取FragmentManager
     *
     * @return
     */
    fun getSDFragmentManager(): SDFragmentManager {
        if (mFragmentManager == null) {
            mFragmentManager = SDFragmentManager(supportFragmentManager)
        }
        return mFragmentManager as SDFragmentManager
    }

    /**
     * 简化Toast
     */
    fun showToast(message: String) {
        if (!SDActivityManager.instance.isEmpty) {
            Toast.makeText(SDActivityManager.instance.lastActivity, message, Toast.LENGTH_SHORT)
                .show()
        }
    }

    /**
     * 结束最后一个activity 或者指定一个activity
     */
    fun finish(view: View? = null, cls: Class<*>? = null) {
        if (view == null) {
            if (cls == null) SDActivityManager.instance.finishLastActivity()
            else SDActivityManager.instance.finishActivity(cls)
        } else {
            if (cls == null) view.setOnClickListener { SDActivityManager.instance.finishLastActivity() }
            else view.setOnClickListener { SDActivityManager.instance.finishActivity(cls) }
        }

    }

    /**
     * 页面跳转
     */
    fun startActivity(
        clz: Class<*>,
        bundle: Bundle? = null,
        view: View? = null,
        requestCode: Int = 0,
        flags: List<Int> = listOf(),
        animationStartType: AnimationActivityType = AnimationActivityType.RIGHT,
        animationEndType: Int = R.anim.animo_no
    ) {
        IntentUtil.startActivity(
            clz,
            bundle,
            requestCode,
            flags,
            view,
            animationStartType = animationStartType,
            animationEndType = animationEndType
        )
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun onEventMainThread(event: SDBaseEvent) {
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    override fun onResume() {
        super.onResume()
        SDActivityManager.instance.onResume(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        overridePendingTransition(0, R.anim.dialog_exit_sliding_to_bottom)
        SDActivityManager.instance.onDestroy(this)
        SDEventManager.unregister(this)
    }
}
